<template>
  <div class="login">
      <van-nav-bar title="登录"/>

        <van-cell-group>
          <van-field
            v-model="username"
            required
            label="账号"
            placeholder="请输入账号"
            :error-message="username_errmsg"
          />
          <van-field
            v-model="password"
            required
            label="密码"
            placeholder="请输入密码"
            :error-message="password_errmsg"
          />
      </van-cell-group>

    <div class="btn-row">
      <van-button type="info" @click="submit">登录</van-button>
      <!-- <van-button type="info" @click="getUserInfo">获取用户信息</van-button> -->
    </div>
  </div>
</template>

<script>
import { reqLogin, reqGetProfile } from '@/api/user.js'
import { mapMutations } from 'vuex'
export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: '',
      username_errmsg: '',
      password_errmsg: ''
    }
  },
  methods: {
    ...mapMutations(['setTokenInfo', 'setUserInfo']),
    validate () {
      if (this.username === '') {
        this.username_errmsg = '亲，请输入账号'
        return false
      }
      // if (!/^1\d{10}$/.test(this.mobile)) {
      //   this.mobile_errmsg = '亲，请输入正确的11位数字'
      //   return false
      // }
      this.username_errmsg = ''
      if (this.password === '') {
        this.password_errmsg = '亲，请输入密码'
        return false
      }
      // if (!/^\d{6}$/.test(this.code)) {
      //   this.code_errmsg = '亲，请输入正确的6位数字'
      //   return false
      // }
      this.password_errmsg = ''
      return true
    },
    async submit () {
      if (!this.validate()) {
        return
      }
      this.$toast.loading({
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '加载中...',
        forbidClick: true
      })
      const res = await reqLogin(this.username, this.password)
      if (res.data.code === 1) {
        this.setTokenInfo(res.data.data)
        this.setUserInfo(res.data.data)
        // 一个页面上只有一个toast, 它会把上面的Loading状态覆盖掉  this.$route.query.backto
        const backto = '/question'
        this.$router.push(backto)
        this.$toast.success('登录成功')
      } else {
        this.$toast.fail(res.data.info)
      }
    },
    async getUserInfo () {
      const res = await reqGetProfile()
    }

  }

}
</script>

<style lang='scss' scoped>
.login{
  .btn-row{
    margin: 20px;
    .van-button{
    width: 100%;
    border-radius: 5px;
    }
  }
}

</style>
